<template>
  <div>
    <Modal :value="showModal" :title="handleType" @on-visible-change="changeVisible">
      <Form ref="form" :model="formData" :rules="ruleCustom" :label-width="70">
        <FormItem style="display: none" v-if="formData.id">
          <label>
            <Input v-model="formData.id" :value="formData.id"/>
          </label>
        </FormItem>
        <FormItem label="账号" prop="username">
          <label>
            <Input v-model="formData.username" v-if="readonly" disabled placeholder="请填写账号"/>
            <Input v-model="formData.username" v-else clearable placeholder="请填写账号"/>
          </label>
        </FormItem>
        <FormItem label="姓名" prop="nick_name">
          <label>
            <Input v-model="formData.nick_name" clearable placeholder="请填写用户姓名"/>
          </label>
        </FormItem>
        <FormItem label="邮箱" prop="email">
          <label>
            <label>
              <Input v-model="formData.email" clearable placeholder="请填写用户邮箱"/>
            </label>
          </label>
        </FormItem>
        <Button
          long
          type="primary"
          size="large"
          @click="handleSubmit('form')">确认
        </Button>
      </Form>
      <div slot="footer"/>
    </Modal>
  </div>
</template>

<script>
  export default {
    name: 'AddUser',
    props: {
      showModal: {
        type: Boolean,
        default: false
      },
      handleType: {
        type: String,
        default: '编辑'
      },
      readonly: {
        type: Boolean,
        default: true
      },
      formData: {
        type: Object,
        default() {
          return {}
        }
      }
    },
    mounted() {
    },
    data() {
      return {
        loading: true,
        ruleCustom: {
          username: [
            {required: true, message: '账号必填', trigger: 'blur'}
          ],
          nick_name: [
            {required: true, message: '姓名必填', trigger: 'blur'},
          ],
          email: [
            {required: true, message: '邮箱必填', trigger: 'blur'},
            {
              validator: (rule, value, callback) => {
                let reg = new RegExp('^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$')
                if (!reg.test(value)) {
                  callback(new Error('邮箱格式不正确'))
                } else {
                  callback()
                }
              }, trigger: 'change'
            }
          ],
        }
      }
    },
    methods: {
      handleSubmit(name) {
        this.$refs[name].validate((valid) => {
          if (valid) {
            this.$emit('handleSubmit', this.formData)
          } else {
            return false
          }
        })
      },
      changeVisible: function (val) {
        this.$refs['form'].resetFields()
        this.$emit('changeVisible', val)
      },
    }
  }
</script>

<style scoped>

</style>
